package com.wt.easyadmin.wx;

import java.security.spec.AlgorithmParameterSpec;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.authz.UnauthorizedException;
import org.apache.tomcat.util.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import com.wt.easyadmin.common.Constants;
import com.wt.easyadmin.common.utils.HttpUtil;
import com.wt.easyadmin.common.utils.JwtUtil;
import com.wt.easyadmin.common.utils.WebUtil;

/**
 * 微信工具类
 * @author: create by wangtao
 * @version: v1.0
 * @description: com.wt.easyadmin.wx
 * @date:2021年2月10日
 */
public class WxUtils {

	private static Logger log = LoggerFactory.getLogger(WxUtils.class);
	
	/**
	 * 解密方法
	 * @param encrypted
	 * @param session_key
	 * @param iv
	 * @return
	 * @throws Exception
	 */
	public static String decrypt(String encrypted, String session_key, String iv) throws Exception {
	 
		byte[] encrypData = Base64.decodeBase64(encrypted);
		byte[] ivData = Base64.decodeBase64(iv);
		byte[] sessionKey = Base64.decodeBase64(session_key);
		AlgorithmParameterSpec ivSpec = new IvParameterSpec(ivData);
		Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
		SecretKeySpec keySpec = new SecretKeySpec(sessionKey, "AES");
		cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
		// 解析解密后的字符串
		return new String(cipher.doFinal(encrypData), "UTF-8");
	}
	
	/**
	 * 登录凭证校验
	 * @param code
	 * @return
	 */
	public static String getSessionByCode(String code) {
		String url = WxConts.CODE2SESSION.replace("JSCODE", code);//拼接请求地址参数
		log.debug("请求地址：{}", url);
		String data = HttpUtil.get(url);// 发送请求
		if(data.contains("errcode")) {
			throw new UnauthorizedException("code有误");
		}
		log.debug("请求结果：{}", data);
		return data;
	}
	
	/**
	 * 获取token
	 * @return
	 */
	public static String getToken() {
		HttpServletRequest req = WebUtil.getInstance().getRequest();
		String token = req.getHeader(Constants.JWT_TOKEN_KEY);
		return token;
	}
	
	/**
	 * 获取openid
	 * @return
	 */
	public static String getOpenid() {
		return JwtUtil.getUserId(getToken());
	}
	
}
